<script setup lang="ts">
import { imageTypes } from '@/common'
import { uploadImageAPI } from '@/services/consult'
import type { Picture } from '@/types/consult'
import { showFailToast, showLoadingToast } from 'vant'
import type {
  UploaderAfterRead,
  UploaderBeforeRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { ref } from 'vue'

defineProps<{
  disabled: boolean
}>()
const emits = defineEmits<{
  (e: 'sendText', text: string): void
  (e: 'sendImage', pictures: Picture): void
}>()
// 上传的文字内容
const textValue = ref('')
// 发送文字消息
const sendText = () => {
  if (textValue.value) {
    emits('sendText', textValue.value)
    textValue.value = ''
  }
}
// 图片上传
// 图片上传前的类型判断
const beforeRead: UploaderBeforeRead = (file?: File | File[]) => {
  if (Array.isArray(file)) return
  if (file && !imageTypes.includes(file.type)) {
    showFailToast('上传图片的格式只能为jpeg,gif,bmp,png,webp')
    return false
  }
  return true
}
// 文件读取完成后的回调函数
const afterRead: UploaderAfterRead = async (
  item: UploaderFileListItem | UploaderFileListItem[]
) => {
  if (Array.isArray(item)) return
  // 需要调用接口上传图片
  if (item.file) {
    try {
      const t = showLoadingToast('上传中...')
      const { data } = await uploadImageAPI(item.file)
      // 上传成功之后将发送自定义事件给父组件
      // 关闭loading状态
      t.close()
      emits('sendImage', data)
    } catch (error) {
      console.log(error)
    }
  }
}
</script>

<template>
  <div class="room-footer-page">
    <van-field
      v-model.trim="textValue"
      :disabled="disabled"
      placeholder="问医生"
      class="input"
      @keyup.enter="sendText"
      autocomplete="off"
    />
    <van-uploader
      :before-read="beforeRead"
      :after-read="afterRead"
      :disabled="disabled"
      upload-icon="photo-o"
      class="upload"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-footer-page {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 60px;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  padding: 0 16px;
  box-sizing: border-box;
  z-index: 999;
  .input {
    display: flex;
    align-items: center;
    background-color: #f6f7f9;
    height: 40px;
    border-radius: 20px;
    color: #c9cacd;
    margin-right: 10px;
    &.van-cell {
      padding: unset;
    }
    ::v-deep() {
      .van-field__value {
        padding-left: 15px;
      }
    }
  }

  .upload {
    width: 24px;
    height: 27px;
    ::v-deep() {
      .van-uploader__upload {
        background: none;
        height: 100%;
        &-icon {
          color: var(--cp-tag);
        }
      }
    }
  }
}
</style>
